package com.gollum.web.controller.auth;

import com.gollum.common.domain.response.RestResponse;
import com.gollum.common.utils.MessageUtils;
import com.gollum.common.utils.ServletUtils;
import com.gollum.common.web.controller.BaseController;
import com.gollum.system.domain.response.LoginUser;
import com.gollum.web.service.AuthService;
import com.gollum.web.service.TokenService;
import com.gollum.system.domain.request.LoginRequest;
import com.gollum.system.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证controller
 *
 * @author Herther
 * @version 1.0.0
 * @createTime 2022年08月27日 22:30:00
 */
@Api(tags = "认证中心")
@RestController
@RequestMapping("/auth")
public class AuthController extends BaseController {

    @Autowired
    protected AuthService authService;

    @Autowired
    protected SysRoleService sysRoleService;

    @Autowired
    protected TokenService tokenService;


    @PostMapping("/login")
    @ApiOperation(value = "登录")
    public RestResponse toLogin(@RequestBody @Validated LoginRequest loginRequest){
        // 生成令牌
        String token = authService.login(loginRequest.getUsername(), loginRequest.getPassword(),loginRequest.getCode(),loginRequest.getToken());
        return RestResponse.success(token).setMsg(MessageUtils.getMsg("resp.login_success"));
    }


    @GetMapping("/getInfo")
    @ApiOperation(value = "获取登录的个人信息")
    public RestResponse getInfo(){
        Map<String,Object> result = getDataMap(tokenService.getLoginUser(ServletUtils.getRequest()));
        return RestResponse.success(result);
    }

    /**
     * 获取返回的信息，包含权限角色用户信息
     * @auther: Herther
     * @since 1.0.0
     * @date: 2022/9/6 21:57
     */
    private Map<String,Object> getDataMap(LoginUser loginUser){
        HashMap<String, Object> resultDatas = new HashMap<>(3);
        resultDatas.put("user",loginUser.getUser());
        resultDatas.put("permissions", loginUser.getPermissions());
        //如果不是超级管理员则需要查询数据库获取角色
        if (loginUser.getUser().isAdmin()){
            resultDatas.put("roles", "admin");
            return resultDatas;
        }
        //查询
        resultDatas.put("roles", sysRoleService.getRoleSetByUser(loginUser.getUserId()));
        return resultDatas;
    }
}
